<?php
function render_template($templatefile, $variables)
{
	$templatedata = implode("", file("templates/$templatefile"));
	foreach ($variables as $key => $value)
	{
		$templatedata = str_replace($key, $value, $templatedata);
	}
	echo evaluate_and_capture($templatedata);
}

function get_template($templatefile, $variables)
{
	$templatedata = implode("", file("templates/$templatefile"));
	foreach ($variables as $key => $value)
	{
		$templatedata = str_replace($key, $value, $templatedata);
	}
	return evaluate_and_capture($templatedata);
}

function evaluate_and_capture($html_php)
{
	$script = "?>" . $html_php . "<?php ;";
	ob_start();
    eval($script);
    return ob_get_clean();
}

function get_file($file)
{
	if (!file_exists($file))
		return "";
	$filedata = implode("", file($file));
	return $filedata;
}

function generate_login()
{
	global $loggedin, $userinfo;
	if ($loggedin)
		return get_template("loginform_out.inc", array(
			'$name' => $userinfo['realname']));
	else
		return get_template("loginform_in.inc", array());
}

function obfuscate_email_addresses($original)
{
	$count = preg_match_all("/<a\\ href=\"mailto:(.*)\">(.*)<\\/a>/", $original, $matches, PREG_SET_ORDER);	
	if ($count == 0)
		return $original;
	
	$original2 = $original;
	$counter = 0;
	foreach ($matches as $match)
	{
		$atag = $match[0];
		$email = $match[1];
		$text = $match[2];
		$id = md5($email . $text . $counter);
		$newtag = "<span id=\"$id\"><a href=\"mailto:" . 
			obfuscate_email_address_lame($email) . "\">" . obfuscate_email_address_lame($text) . '</a></span>';
		$newtag .= '<script type="text/javascript">' . "\n<!--\n" . "document.getElementById(\"$id\").innerHTML=";
		$email = obfuscate_email_address($email);
		$text = obfuscate_email_address($text);
		$scriptedtag = "<a href=\"mailto:$email\">$text</a>";
		for ($n = 0; $n < strlen($scriptedtag); $n++)
			$newtag .= "'" . $scriptedtag[$n] . "' + ";
		$newtag .= " '';\n//-->\n</script>";
		$original2 = str_replace($atag, $newtag, $original2);
		$counter++;
	}
		
	return $original2;
}

function obfuscate_email_address($email)
{
	$obfuscated = '';
	for ($n = 0; $n < strlen($email); $n++)
	{
		$obfuscated .= '&#' . ord($email[$n]) . ';';
	}
	return $obfuscated;
}

function obfuscate_email_address_lame($email)
{
	global $config_antispam_removemetext;
	if (strpos($email, '@') === false)
		return $email;
	$parts = explode('@', $email);
	return $parts[0] . '@' . $config_antispam_removemetext . $parts[1];
}
?>